//
//  WH_NewDetailViewController.m
//  App_6.23
//
//  Created by wanghao on 16/7/19.
//  Copyright © 2016年 wanghao. All rights reserved.
//

#import "WH_NewDetailViewController.h"
#import "WH_NewDetailHeader.h"
#import "WH_Home.h"
#import "WH_WebViewController.h"
#import "WH_HomeDetailCell.h"
#import "WH_PastViewController.h"
#import "WH_ShareOrderController.h"
#import "WH_HomeDetailController.h"
#import "TimeModel.h"
#import "WH_PersonalViewController.h"

@interface WH_NewDetailViewController ()<UITableViewDataSource,UITableViewDelegate>

@property (nonatomic, strong) UITableView *myTableView;
@property (nonatomic, strong) WH_NewDetailHeader *detailHeaderV;
@property (nonatomic, strong) NSMutableArray *imageArr;
@property (nonatomic, assign) BOOL isUploading;
@property (nonatomic, strong) NSMutableArray *strArr;
@property (nonatomic, copy) NSString *webUrl;//图文详情
@property (nonatomic, strong) NSMutableArray *recordArr;


@end

@implementation WH_NewDetailViewController

-(void)viewWillAppear:(BOOL)animated{
    
    
    [self.tabBarController.tabBar setHidden:YES];
}
-(void)viewWillDisappear:(BOOL)animated{
    
    
    [self.tabBarController.tabBar setHidden:NO];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.imageArr = [NSMutableArray array];
    self.recordArr = [NSMutableArray array];
    self.strArr = [NSMutableArray arrayWithObjects:@"图文详情", @"往期揭晓", @"晒单分享", nil];
    [self createTab];
    [self bottomView];
    [self registerNSNotificationCenterD];
    [self createHub];
    [self hubShow];
}
#pragma mark - 创建视图

-(void)createTab{
    
    self.myTableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    self.myTableView.delegate = self;
    self.myTableView.dataSource = self;
    self.myTableView.rowHeight = 50;
    self.myTableView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_myTableView];
    
    [self.myTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.right.top.equalTo(@0);
        make.bottom.equalTo(@-49);
    }];
    [self.myTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
    [self.myTableView registerClass:[WH_HomeDetailCell class] forCellReuseIdentifier:@"NewDetailCell"];
    self.myTableView.sectionHeaderHeight = 10;
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(downLoadMJ)];
    self.myTableView.mj_header = header;
    [self.myTableView.mj_header beginRefreshing];
    
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(upLoadMJ)];
    self.myTableView.mj_footer = footer;
    
    [self.myTableView setHidden:YES];
}

-(void)bottomView{
    
    UIView *bottomView = [UIView new];
    bottomView.tag = 10011;
    [self.view addSubview:bottomView];
    bottomView.backgroundColor = [UIColor whiteColor];
    [bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.right.mas_equalTo(@0);
        make.bottom.mas_equalTo(@0);
        make.height.mas_equalTo(49);
    }];
    UIView *line = [UIView new];
    [bottomView addSubview:line];
    line.backgroundColor = [UIColor colorWithRed:0.86 green:0.85 blue:0.86 alpha:1];
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.right.top.mas_equalTo(@0);
        make.height.mas_equalTo(@1);
    }];
    UILabel *lab = [[UILabel alloc] init];
    lab.text = @"新一期正在火热进行中...";
    lab.font = [UIFont systemFontOfSize:13.f];
    [bottomView addSubview:lab];
    [lab mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.equalTo(@6);
        make.centerY.equalTo(bottomView);
        make.width.equalTo(@(SCREEN_WIDTH/2-9));
        make.height.equalTo(@30);
    }];
    
    
    UIButton *duobaoBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [bottomView addSubview:duobaoBtn];
    duobaoBtn.backgroundColor = [UIColor colorWithRed:0.9 green:0.19 blue:0.29 alpha:1];
    [duobaoBtn setTitle:@"立即前往" forState:UIControlStateNormal];
    duobaoBtn.layer.cornerRadius = 5;
    [duobaoBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [duobaoBtn addTarget:self action:@selector(toDetail:) forControlEvents:UIControlEventTouchUpInside];
    [duobaoBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.mas_equalTo(6);
        make.right.bottom.mas_equalTo(@-6);
        make.width.equalTo(@(SCREEN_WIDTH/3));
    }];
    
    [bottomView setHidden:YES];
    
}

#pragma mark - 立即前往

-(void)toDetail:(UIButton *)btn{
    
    WH_HomeDetailController *homeDetail = [[WH_HomeDetailController alloc] init];
    
    homeDetail.productID = self.detailNew.product_id;
    //homeDetail.faceImage = homeModel.product_image;
    //homeDetail.faceTitle = homeModel.product_name;
    [self.navigationController pushViewController:homeDetail animated:YES];
    
    
}
#pragma mark - 刷新/加载

-(void)downLoadMJ{
    
    NSLog(@"下拉刷新");
    
    self.isUploading = NO;
    //[self postWorking];
    [self postData];
}

-(void)upLoadMJ
{
    NSLog(@"上拉加载");
    self.isUploading = YES;
    
}

#pragma mark - Post产品详情

-(void)postData{
    
    NSString *body = [NSString stringWithFormat:@"action=product&product_id=%@",self.detailNew.product_id];
    [WH_AppTools postUrl:URLstr body:body result:HXJSON requestStyle:HXRequestString headerFile:nil success:^(id result) {
        
        if (self.isUploading == NO){
            
            [self.imageArr removeAllObjects];
            [self.detailHeaderV removeFromSuperview];
        }
        
        NSDictionary *dic = result;
        NSDictionary *product_array = [dic objectForKey:@"product_array"];
        NSMutableArray *product_image_array = [product_array objectForKey:@"product_image_array"];
        
        WH_Home *homeDetail = [WH_Home modelWithDictionary:product_array];
        if (_detailNew.cur_time.length != 0) {
            
            self.detailHeaderV = [[WH_NewDetailHeader alloc] initWithFrame:CGRectMake(0, 0, self.myTableView.frame.size.width, 450)];
            [self.detailHeaderV createModel:_detailNew timeModel:_timeCount];
            self.myTableView.tableHeaderView = _detailHeaderV;
            
        }else{
            self.detailHeaderV = [[WH_NewDetailHeader alloc] initWithFrame:CGRectMake(0, 0, self.myTableView.frame.size.width, 525)];
            self.myTableView.tableHeaderView = _detailHeaderV;
            [self.detailHeaderV luckView:_detailNew];
        }
        [self.detailHeaderV createSubViews:product_image_array];
        self.webUrl = homeDetail.product_description;
        
        [self postRecord:_detailNew.product_period productID:_detailNew.product_id];
        [self.myTableView setHidden:NO];
        UIView *botV = [self.view viewWithTag:10011];
        [botV setHidden:NO];
        [self hubDismiss];
        [self endFresh];

    } failure:^(NSError *error) {
        
        
    }];
    
}

#pragma mark - 通知中心
- (void)registerNSNotificationCenterD {
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(notificationCenterEventDetail)
                                                 name:NOTIFICATION_TIME_CELL
                                               object:nil];
}

- (void)dealloc {
    NSLog(@"移除通知");
    [[NSNotificationCenter defaultCenter] removeObserver:self name:NOTIFICATION_TIME_CELL object:nil];
}

- (void)notificationCenterEventDetail {
    
    self.detailHeaderV.rateLabel.text = [NSString stringWithFormat:@"%@",[_timeCount currentTimeString]];
    
    if ([[_timeCount currentTimeString] isEqualToString:@"00:00:10"]) {
        
        [self postLotteryDetail];
        
    }
    
}

#pragma mark - 获取开奖数据 POST

-(void)postLotteryDetail{
    
    NSString *body = [NSString stringWithFormat:@"action=lottery&product_period=%@",_detailNew.product_period];
    NSLog(@"_detailNew.product_period=%@",_detailNew.product_period_no);

    [WH_AppTools postUrl:URLstr body:body result:HXJSON requestStyle:HXRequestString headerFile:nil success:^(id result) {
        
        NSLog(@"result = %@", result);
        NSDictionary *dic = result;
        NSArray *order_array = [dic objectForKey:@"order_array"];
        for (NSDictionary *dic in order_array) {
            
            WH_Home *newest = [WH_Home modelWithDictionary:dic];
            _detailNew = newest;

        }
        _detailNew.cur_time = @"";
        [self postData];
    } failure:^(NSError *error) {
        
        
    }];
    
    
}

#pragma mark - 全部记录

-(void)postRecord:(NSString *)period productID:(NSString *)productID{
    
    NSString *body = [NSString stringWithFormat:@"action=product_record&product_id=%@&product_period=%@",productID,period];
    NSLog(@"NewDetailproductID=%@",_detailNew.product_id);
    NSLog(@"NewDetailproduct_period=%@",_detailNew.product_period);


    [WH_AppTools postUrl:URLstr body:body result:HXJSON requestStyle:HXRequestString headerFile:nil success:^(id result) {
        //NSLog(@"=====%@",result);
        if (self.isUploading == NO){
            
            [self.recordArr removeAllObjects];
        }
        
        NSDictionary *dic = result;
        NSArray *product_record_array = [dic objectForKey:@"product_record_array"];
        for (NSDictionary *dic in product_record_array) {
            
            WH_Home *record = [WH_Home modelWithDictionary:dic];
            [self.recordArr addObject:record];
        }
        [self.myTableView reloadData];
    } failure:^(NSError *error) {
        
        
    }];
    
}
#pragma mark - 结束刷新

-(void)endFresh{
    
    [self.myTableView.mj_footer endRefreshing];
    [self.myTableView.mj_header endRefreshing];
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 2;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    if (section == 0) {
        
        return self.strArr.count;
    }
    return self.recordArr.count+1;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *indexCell = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:indexCell];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    if (indexPath.section == 0) {
        
        cell.textLabel.text = self.strArr[indexPath.row];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    if(indexPath.section == 1)
    {
        if (indexPath.row == 0) {
            
            cell.textLabel.text = @"所有参与记录";
            cell.accessoryType = UITableViewCellAccessoryNone;
            
        }else{
            
            WH_HomeDetailCell *detailcell = [tableView dequeueReusableCellWithIdentifier:@"NewDetailCell"];
            detailcell.record = self.recordArr[indexPath.row-1];
            return detailcell;
        }
    }
    return cell;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    UIView *headview = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 10)];
    headview.backgroundColor = [UIColor colorWithRed:0.97 green:0.97 blue:0.97 alpha:1];
    return headview;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGFloat sectionHeaderHeight = 40;
    if (scrollView.contentOffset.y<=sectionHeaderHeight&&scrollView.contentOffset.y>=0)
    {
        scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
    }
    else if (scrollView.contentOffset.y>=sectionHeaderHeight)
    {
        scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0);
    }
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section == 0) {
        
        if (indexPath.row == 0) {
            
            WH_WebViewController *webView = [[WH_WebViewController alloc] init];
            webView.urlStr = self.webUrl;
            [self.navigationController pushViewController:webView animated:YES];
        }else if (indexPath.row == 1){
            
            WH_PastViewController *pastVC = [[WH_PastViewController alloc] init];
            pastVC.pastID = _detailNew.product_id;
            [self.navigationController pushViewController:pastVC animated:YES];
            
        }else if (indexPath.row == 2){
            
            WH_ShareOrderController *shareVC = [[WH_ShareOrderController alloc] init];
            shareVC.showID = _detailNew.product_id;
            
            [self.navigationController pushViewController:shareVC animated:YES];
            
        }
        
    }else{
        
        WH_PersonalViewController *personVC = [[WH_PersonalViewController alloc] init];
        WH_Home *personH = self.recordArr[indexPath.row-1];
        personVC.personID = personH.user_id;
        personVC.personImg = personH.user_avatar;
        personVC.personName = personH.user_name;
        [self.navigationController pushViewController:personVC animated:YES];
    }
    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
